/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <algorithm>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QResizeEvent>
#include "imageeditarea.h"
#include "editortool.h"
#include "log.h"

ImageEditArea::ImageEditArea(QWidget* parent) : QWidget(parent),
	m_scale(1)
{
	setMouseTracking(true);
}

ImageEditArea::~ImageEditArea()
{
}

void ImageEditArea::drawTool(QPainter* painter)
{
	if(m_currentTool)
		m_prevRect = m_currentTool->draw(painter);
}

void ImageEditArea::paintEvent(QPaintEvent* event)
{
	QRect r = event->rect();
	QRect imageRect = QRect(QPoint(0, 0), m_image.size() * m_scale);
	QPainter painter(this);
	painter.drawImage(r, m_image, r);
	drawTool(&painter);
}

void ImageEditArea::setImage(const QImage& image)
{
	m_image = image;
	updateSize();
}

QImage ImageEditArea::image()
{
	return m_image;
}

//QPaintDevice* ImageEditArea::paintDevice()
//{
//	return &m_image;
//}

QImage* ImageEditArea::imagePtr()
{
	return &m_image;
}

QSize ImageEditArea::sizeHint()
{
	return m_image.size() * m_scale;
}

void ImageEditArea::updateSize()
{
	resize(m_image.size() * m_scale);
	setMinimumSize(m_image.size() * m_scale);
	setMaximumSize(m_image.size() * m_scale);
	updateGeometry();
}

void ImageEditArea::mouseMoveEvent(QMouseEvent* event)
{
	if(m_currentTool)
	{
		m_currentTool->mouseMove(event->pos());
		update(m_prevRect);
	}
	m_mouse = event->pos();
}

void ImageEditArea::mousePressEvent(QMouseEvent* event)
{
	if(m_currentTool)
		m_currentTool->mousePress(event->pos());
	update();
}

void ImageEditArea::mouseReleaseEvent(QMouseEvent* event)
{
	if(m_currentTool)
		m_currentTool->mouseRelease(event->pos());
	update();
}

void ImageEditArea::setLineWidth(int width)
{
	m_lineWidth = width;
}

void ImageEditArea::setForegroundColor(QColor color)
{
	m_foreground = color;
	QPen pen = m_currentTool->pen();
	pen.setColor(color);
	m_currentTool->setPen(pen);
}

void ImageEditArea::setTool(EditorToolPtr tool)
{
	m_currentTool = tool;
}

